package com.example.wearing.user;

import static cn.bmob.v3.Bmob.getApplicationContext;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.ViewModelProvider;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wearing.R;
import com.example.wearing.index.IndexViewModel;
import com.example.wearing.javabean.Clothes;
import com.example.wearing.javabean.Match;
import com.example.wearing.tools.BitmapBinder;
import com.example.wearing.tools.ClothesListAdapter;
import com.example.wearing.tools.ClothesOfMatchAdapter;
import com.example.wearing.tools.ImageUtil;
import com.example.wearing.tools.MatchListAdapter;
import com.example.wearing.wardrobe.AddClothesActivity;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class UserFragment extends Fragment {
    /*
    任务：
    1、头像：点击头像进行修改,从相册选择——移入设置内
    2、获取用户名
    3、获取单品数量、搭配数量
    4、创建新搭配
        进入新页面，选择上衣、下装、鞋子、饰品等
    5、搭配的修改删除
    6、进入设置
    */

    private UserViewModel mViewModel;
    private TextView userName, clothesNum, matchNum;
    private GridView matchListView;
    private ImageView userImg, setImg;
    private Button addMatchBtn;
    private ProgressBar bar;
    private TextView nodata;
    private static final String TAG = "UserFragment";

    private ArrayList<Match> matchList = new ArrayList<>();
    private Handler handler;
    private String userNameStr, userImgStr;
    private int m_id, userId;
    private String jdbcUrl, jdbcUser, jdbcPassword;
    private MatchListAdapter matchListAdapter;

    public static UserFragment newInstance() {
        return new UserFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.user_fragment, container, false);
        userName = view.findViewById(R.id.userName);
        clothesNum = view.findViewById(R.id.clothesNum);
        matchNum = view.findViewById(R.id.matchNum);
        userImg = view.findViewById(R.id.userImg);
        setImg = view.findViewById(R.id.setImg);
        addMatchBtn = view.findViewById(R.id.addMatchBtn);
        matchListView = view.findViewById(R.id.myMatchList);
        bar = view.findViewById(R.id.progressBar);
        nodata = view.findViewById(R.id.nodataText);
        return view;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        // TODO: Use the ViewModel

        init();
        getClothesAndMatchNum();
        initMatchAdapter();

        //进入设置页面
        setImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), SettingActivity.class);
                startActivityForResult(intent, 3);
            }
        });

        //进入添加搭配界面
        addMatchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent addMatchIntent = new Intent(getActivity(), AddMatchActivity.class);
                addMatchIntent.putExtra("m_flag", 1);
                startActivityForResult(addMatchIntent, 10);
            }
        });


        handler = new Handler(){
            @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
            @Override
            public void handleMessage(@NonNull Message msg){
                if(msg.what == 1){
                    Log.i(TAG, "handleMessage: 收到消息——衣物数量");
                    int res = (int) msg.obj;
                    clothesNum.setText(String.valueOf(res));
                }else if(msg.what == 2){
                    Log.i(TAG, "handleMessage: 收到消息——搭配数量");
                    int res = (int) msg.obj;
                    matchNum.setText(String.valueOf(res));
                }else if(msg.what == 3){
                    //接收消息
                    int res = (int) msg.obj;
                    if(res == 1){
                        Log.i(TAG, "done: 查询match成功");
                        Log.i(TAG, "handleMessage: 衣物数量:"+matchList.size());
                        matchListAdapter.notifyDataSetChanged();

                    }else if(res == 2){
                        //查询帖子失败
                        Log.i(TAG, "done: 查询match失败");
                        Toast.makeText(getActivity().getApplicationContext(), "刷新失败", Toast.LENGTH_SHORT).show();
                    }

                    //切换显示状态
                    bar.setVisibility(View.GONE);
                    //没有获得数据时显示
                    matchListView.setEmptyView(nodata);
                    matchListView.setVisibility(View.VISIBLE);
                }else if(msg.what == 4){
                    Log.i(TAG, "handleMessage: 收到删除某件衣物的消息");
                    //更新适配器
                    matchListAdapter.notifyDataSetChanged();
                    //更新搭配数目
                    String matchNumTmp = matchNum.getText().toString();
                    int matchNumTmpInt = Integer.valueOf(matchNumTmp)-1;
                    matchNum.setText(matchNumTmpInt+"");
                }
                super.handleMessage(msg);
            }
        };

        Thread thread = new Thread(selectMatchRun);
        thread.start();

    }

    public void init(){
        //检查sharedPreference,获取用户名
        SharedPreferences sp = getActivity().getSharedPreferences("user", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(getActivity());
        userNameStr = sp.getString("user_name","");
        userImgStr = sp.getString("user_img","");
        userId = sp.getInt("user_id",0);
        jdbcUrl = sp.getString("jdbc_url", "");
        jdbcUser = sp.getString("jdbc_user","");
        jdbcPassword = sp.getString("jdbc_password","");
        userName.setText(userNameStr);
        Bitmap bitmap = ImageUtil.base64ToImage(userImgStr);//设置头像
        userImg.setImageBitmap(bitmap);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode == 3 && resultCode == 4){
            //从 设置 页面返回
            //刷新界面
            //检查sharedPreference,获取用户头像
            SharedPreferences sp = getActivity().getSharedPreferences("user", Activity.MODE_PRIVATE);
            PreferenceManager.getDefaultSharedPreferences(getActivity());
            String usernameStr = sp.getString("user_name","");
            userName.setText(usernameStr);
            String userImgStr = sp.getString("user_img","");
            Bitmap bitmap = ImageUtil.base64ToImage(userImgStr);//设置头像
            userImg.setImageBitmap(bitmap);
        }else if(requestCode == 10 && resultCode == 20){
            //添加搭配后，更新衣物的信息，更新adapter
            Thread thread = new Thread(selectMatchRun);
            thread.start();
            //更新搭配数目
            String matchNumTmp = matchNum.getText().toString();
            int matchNumTmpInt = Integer.valueOf(matchNumTmp)+1;
            matchNum.setText(matchNumTmpInt+"");
        } else if(requestCode == 30 && resultCode == 40){
            //更改match信息后，更新adapter
            Thread thread = new Thread(selectMatchRun);
            thread.start();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //初始化每个分类下 衣物列表
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initMatchAdapter() {

        matchListAdapter = new MatchListAdapter(getActivity(), R.layout.clothes_of_match, matchList);
        matchListView.setAdapter(matchListAdapter);

        //点击事件
        matchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i(TAG, "onItemClick: 点击position:"+position);
                Match alterMatch = (Match) matchListView.getItemAtPosition(position);
                //跳转修改界面
                Intent alterMatchIntent = new Intent(getActivity(), AddMatchActivity.class);
                alterMatchIntent.putExtra("m_flag", 2);
                alterMatchIntent.putExtra("m_id", alterMatch.getM_id());
                alterMatchIntent.putExtra("m_time", alterMatch.getM_time());
                alterMatchIntent.putExtra("m_style", alterMatch.getM_style());
                Bundle bundle = new Bundle();
                Bitmap bitmap = ImageUtil.base64ToImage(alterMatch.getM_img());
                bundle.putBinder("m_img", new BitmapBinder(bitmap));
                alterMatchIntent.putExtras(bundle);
                startActivityForResult(alterMatchIntent, 30);

            }
        });

        matchListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("提示")
                        .setMessage("请确认是否删除当前数据？")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Log.i(TAG, "onClick: 删除对话框事件处理");
                                Match match = (Match) matchListView.getItemAtPosition(position);
                                m_id = match.getM_id();
                                //删除arraylist中信息
                                matchList.remove(match);
                                //开启线程，从数据库中删除该记录
                                Thread thread2 = new Thread(deleteMatchRun);
                                thread2.start();
                                Log.i(TAG, "onActivityCreated: DB删除记录");
                            }
                        }).setNegativeButton("否", null);
                builder.create().show();

                return true;
            }
        });
        matchListAdapter.notifyDataSetChanged();
    }

    private void getClothesAndMatchNum(){
        //开启线程
        Thread thread = new Thread(getClothesAndMatchNumRun);
        thread.start();
    }

    //获取单品数量、搭配数量——msg1、2
    private Runnable getClothesAndMatchNumRun = new Runnable() {
        @Override
        public void run() {
            int clothesNum=0, matchNum=0;
            //查询数据库中是否存在该用户名——存在弹窗提示
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser ,jdbcPassword);
                String sql = "select count(*) from clothes where c_uid = "+userId;
                Statement st = (Statement)cn.createStatement();
                ResultSet rs = st.executeQuery(sql);
                System.out.println("查找成功");
                if(rs.next())
                    clothesNum = rs.getInt(1);
                rs.close();

                String sql2 = "select count(*) from matches where m_uid = "+userId;
                ResultSet rs2 = st.executeQuery(sql2);
                System.out.println("查找成功");
                if(rs2.next())
                    matchNum = rs2.getInt(1);
                rs2.close();

                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__" + e);
                e.printStackTrace();
            }
            //发送消息
            Message msg = handler.obtainMessage(1, clothesNum);
            handler.sendMessage(msg);
            Message msg2 = handler.obtainMessage(2, matchNum);
            handler.sendMessage(msg2);
            Log.i(TAG, "run: 消息已发送---查询衣物和搭配数量");

        }
    };

    //创建线程类，实现Runnable接口，用于查询所有衣物信息——msg3
    private Runnable selectMatchRun = new Runnable() {
        @Override
        public void run() {
            try {
                Log.i(TAG, "run: 开始查询所有match111");
                Class.forName("com.mysql.jdbc.Driver");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
                String sql = "select * from matches where m_uid="+userId;
                Statement st = (Statement)cn.createStatement();

                int resCode;
                try {
                    ResultSet rs = st.executeQuery(sql);
                    System.out.println("连接数据库成功");

                    rs.last(); // 将光标移动到最后一行
                    int rowCount = rs.getRow(); // 得到当前行号，即结果集记录数
                    Log.i(TAG, "run: 数量rowcount:"+rowCount);
                    rs.beforeFirst();//将光标移回首行

                    matchList.clear();
                    //查询出数据，将其放在List<Match>中，使用adapter将其显示在列表里
                    while (rs.next()){
                        Match match = new Match();
                        match.setM_id(rs.getInt("m_id"));
                        match.setM_img(rs.getString("m_img"));
                        match.setM_time(rs.getString("m_time"));
                        match.setM_style(rs.getString("m_style"));
                        matchList.add(match);
                    }
                    resCode = 1;
                    rs.close();
                } catch (SQLException e) {
                    Log.i(TAG, "run:SQL fail!!!__"+e);
                    e.printStackTrace();
                    resCode = 2;
                }

                //发送消息
                Message msg = handler.obtainMessage(3, resCode);
                handler.sendMessage(msg);
                Log.i(TAG, "run: 消息已发送---查询结果");

                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__"+e);
                e.printStackTrace();
            }
        }
    };

    //长按删除衣物——msg4
    private Runnable deleteMatchRun = new Runnable() {
        @Override
        public void run() {

            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
                String sql = "delete from matches where m_id = "+ m_id;
                Statement st = (Statement) cn.createStatement();
                int result = st.executeUpdate(sql);// 返回值代表收到影响的行数
                System.out.println("删除match——连接数据库成功");

                //发送消息
                Message msg = handler.obtainMessage(4, result);
                handler.sendMessage(msg);
                Log.i(TAG, "run: 消息已发送---删除结果");

                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__" + e);
                e.printStackTrace();
            }
        }
    };
}